const Router = require("koa-router");
const { Reply, Complaint } = require("@models/complaint");
const { BlackList } = require("@models/blacklist");
const { User } = require("@models/user");
const { Admin } = require("@models/admin");
const { Auth } = require("@middlewares/auth");
const { Ip } = require("@services/ip");

const router = new Router({
  prefix: "/v1/complaint",
});
// Complaint.sync({ force: false });
// 留言列表
router.post("/list", new Auth().m, async (ctx, next) => {
  const { page = 1, pageSize = 10, my = false } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const where = my
    ? {
        is_on: true,
        uid: ctx.auth.uid,
      }
    : {
        is_on: true,
      };
  const { count: total, rows } = await Complaint.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "DESC"]],
    include: [
      {
        model: User,
        attributes: ["user_name", "avatar"],
        required: false,
      },
      {
        model: Reply,
        attributes: ["content", "created_at"],
        required: false,
        include: [
          {
            model: Admin,
            attributes: ["admin_name", "avatar"],
            required: false,
          },
        ],
      },
    ],
  });

  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows.map((v) => {
      v.User.BlackList = v.User.BlackList ? 1 : 0;
      return v;
    }),
  };
});

// 留言详情
router.post("/detail", new Auth().m, async (ctx, next) => {
  const { complaint_id } = ctx.request.body;

  const where = {
    is_on: true,
    complaint_id,
  };
  const complaint = await Complaint.findOne({
    where,
    include: [
      {
        model: User,
        attributes: ["user_name", "avatar"],
        required: false,
      },

      {
        model: Reply,
        attributes: ["content", "created_at"],
        required: false,
        include: [
          {
            model: Admin,
            attributes: ["admin_name", "avatar"],
            required: false,
          },
        ],
      },
    ],
  });

  ctx.body = {
    code: 200,
    msg: "获取成功",
    data: complaint,
  };
});

// 留言建议
router.post("/create", new Auth().m, async (ctx) => {
  const { content, imgs } = ctx.request.body;
  const res = await Ip.get(ctx);
  let { nation, province, city, district } = res.data.result.ad_info;
  const area = `${province}${city}`;
  const blacklist = await BlackList.findOne({
    where: {
      uid: ctx.auth.uid,
    },
  });

  if (blacklist) {
    throw new global.errs.AuthFailed("服务器错误，请稍后再试");
  }

  await Complaint.create({
    content: content,
    imgs: imgs,
    area: area,
    uid: ctx.auth.uid,
  });
  ctx.body = {
    code: 200,
    msg: "留言成功",
  };
});

module.exports = router;
